package com.blogs.service;

import java.net.URLEncoder;
import java.util.Map;

import com.blogs.entity.AppConfig;
import com.blogs.entity.BlogPublicEntry;
import com.blogs.entity.MsgEntity;
import com.blogs.entity.SendBlogEntry;
import com.blogs.service.GetMsgTask.onTaskCallBack;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SendBlogs {
	public interface IMsgCallBack {
		public void onSuccess(SendBlogEntry sce);
		public void onFailed();
	}

	private String url = AppConfig.SEND_BLOG_PUBLIC;
	private GetMsgTask getresult;
	private IMsgCallBack callback;
	public SendBlogs(BlogPublicEntry bpe,IMsgCallBack callback) {
		// TODO Auto-generated constructor stub
//		.replace("\n", "<br/>").replace("\r", "<br/>").replace(" ", "&nbsp;").replace("+", "%26nbsp%3b")
		this.callback = callback;
		this.url=url.replace("{0}", bpe.sid)
				.replace("{1}", URLEncoder.encode(bpe.txbTitle))
				.replace("{2}", URLEncoder.encode(bpe.EditorBody.replace("\n", "<br/>").replace("\r", "<br/>").replace(" ", "&nbsp;")))
				.replace("{3}", bpe.name_site_categroy)
				.replace("{4}", URLEncoder.encode(bpe.txbExcerpt))
				.replace("{5}",URLEncoder.encode( bpe.txbTag))
				.replace("{6}", bpe.cbHomeCandidate?"on":"")
				.replace("{7}", bpe.cbIsPublishToSiteHome?"on":"")
				.replace("{8}", bpe.chkDisplayHomePage?"on":"");
//		this.url+=bpe.chkDisplayHomePage?"&cbHomeCandidate=on":"";
//		this.url+=bpe.cbIsPublishToSiteHome?"&cbIsPublishToSiteHome=on":"";
//		this.url+=bpe.chkDisplayHomePage?"&chkDisplayHomePage=on":"";
//		&cbHomeCandidate={6}&cbIsPublishToSiteHome={7}&chkDisplayHomePage={8}
		getresult = new GetMsgTask(taskCallBack);
	}
	public void Send()
	{
		getresult.execute(url);
	}
	private GetMsgTask.onTaskCallBack taskCallBack = new onTaskCallBack() {
		public void onSuccess(String result) 
		{
			GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<Map<String, Object>> msg = null;
			try {
				msg = gson.fromJson(result, MsgEntity.class);
			} catch (Exception e) {
				callback.onFailed();
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				return;
			}
			SendBlogEntry sbe=new SendBlogEntry(msg.data);
			callback.onSuccess(sbe);
		}
		public void onFailed() {
			callback.onFailed();
		}
	};
}
